package cj.web.sc.controllers;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import cj.utils.Constants;
import cj.utils.ImageUtils;
import cj.utils.ReadConfigProperties;
import cj.utils.ReturnUUID;
import cj.web.constants.MemuEnum;
import cj.web.admin.dao.UserInfoDAO;
import cj.web.admin.domain.UserInfo;
import cj.web.login.controllers.BaseController;
import cj.web.sc.dao.SCSellerDAO;
import cj.web.sc.domain.SCSeller;

@Path("/seller")
public class SCSellerController extends BaseController{

	private static Logger logger = Logger.getLogger(SCSellerController.class.getName());
	
	@Autowired
	private SCSellerDAO sellerDao;
	@Autowired
	private UserInfoDAO userInfoDAO;

	@Get("show")
	public String show(Model model,SCSeller sCSeller, HttpServletRequest request)
	{
		model.add("MemuEnum", MemuEnum.scseller);
		return "/views/sc/sellerList.vm";
	}
	
	@Post("list")
	public String list(Model model,SCSeller seller, HttpServletRequest request)
	{
		UserInfo user =  returnSessionObj(request);
		String acount = user.getAccount();
		int userId = user.getId();
		if(Constants.ADMIN.equals(acount)){  //admin账户可看到所有的
			userId = -1;
		}
		List<SCSeller> objs = sellerDao.queryByUserId(seller,userId);
		int size = sellerDao.sizeByUserId(seller,userId);
		
		JSONObject jo = new JSONObject();
		jo.put("data", objs);
		jo.put("draw", seller.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	@Get("create")
	public String create(Model model, HttpServletRequest request)
	{
		UserInfo user =  returnSessionObj(request);
		String acount = user.getAccount();
		int userId = user.getId();
		Map selUsers = new HashMap<>();
		if(Constants.ADMIN.equals(acount)){  //admin账户可给所有登录账号新建商家
			List<UserInfo> users = userInfoDAO.queryAllExcAdmin();
//			List<UserInfo> users = userInfoDAO.queryAll();
			for( UserInfo userInfo : users ){
				selUsers.put(userInfo.getId(), userInfo.getAccount());
			}
		}
		else{                               //普通账号只能为自己建商家
			selUsers.put(userId, acount);
		}
		
		model.add("SelUsers", selUsers);
		model.add("MemuEnum", MemuEnum.scseller);
		return "/views/sc/sellerDetail.vm";
	}
	
	@Post("crtSeller")
	public String crtSeller(Model model,SCSeller seller, HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		SCSeller obj = sellerDao.queryByUserInfoId(seller.getUserInfoId());
		if(obj!=null){
			jo.put("returnFlag", Constants.returnObj.returnFlag_repeat);
			return "@" + jo.toString();
		}
		
		String acount = returnSessionObj(request).getAccount();
		seller.setCreateUser(acount);
		seller.setUpdateUser(acount);
		seller.setDeleteFlag(1);
		
		try {
			sellerDao.create(seller);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@" + jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model, @Param("id") int id, HttpServletRequest request)
	{
		SCSeller obj = sellerDao.queryById(id);
		
		UserInfo userInfo = userInfoDAO.queryById(obj.getUserInfoId());
		Map selUsers = new HashMap<>();
		selUsers.put(obj.getUserInfoId(), userInfo.getAccount());    //账号不可修改
		model.add("SelUsers", selUsers);
		
		model.add("obj", obj);
		model.add("MemuEnum", MemuEnum.scseller);
		return "/views/sc/sellerEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,SCSeller seller, HttpServletRequest request)
	{
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String acount = returnSessionObj(request).getAccount();
		seller.setUpdateUser(acount);
		
		try {
			sellerDao.update(seller);
		} catch (Exception e) {
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		return "@" + jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") int id, HttpServletRequest request)
	{
		SCSeller seller = sellerDao.queryById(id);
		if(seller != null){
			String acount = returnSessionObj(request).getAccount();
			seller.setUpdateUser(acount);
			sellerDao.deleteById(seller);
		}
		
		return "r:show";
	}
	
	@Post("upload")
    public String upload(@Param("uploadimage") MultipartFile file,HttpServletRequest request) {
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		// 判断文件是否为空  
        if (file != null && !file.isEmpty()) {  
            try {  
            	// 文件保存路径  
            	String path = ReadConfigProperties.getValue("uploadFilePath_Marriage");
            	//判断文件是否存在，不存在创建文件
            	Map rep = ReturnUUID.getFolder(path);
            	path = rep.get("allpath").toString();//所在的全路径
            	//文件名
                String fileName =  ReturnUUID.getName(file.getOriginalFilename()); 
                // 转存文件  
                file.transferTo(new File(path+"/"+fileName));
                
                jo.put("filePath", rep.get("filepath")+"/"+fileName);
                
                ImageUtils.scale2(path+"/"+fileName, path+"/s_"+fileName, 100, 100, true);//缩率图
            } catch (Exception e) {
                jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
            }  
        } 
		
		return "@"+jo.toString();
    }
}
